<template>
  <uv-popup ref="popup" @change="change" round="15px" :safeAreaInsetBottom="false">
    <view class="audio-container textCenter">
      <view class="time">{{voiceTime}}s</view>
      <!-- 生成的音频文件 -->
      <view class="main flex alignCenter justifyCenter" v-if="recordContent">
        <uv-image @click="init" src="/static/img/audioDel.png" width="40px" height="40px"></uv-image>
        <view class="playIcon" @click="handleAudio">
          <view class="playNow" v-if="isPlay">
            <view class="pauseIcon">
              <uv-icon name="pause" color="#ffffff" size="30"></uv-icon>
            </view>
          </view>
          <uv-image v-else src="/static/img/audioPlay.png" width="80px" height="80px"></uv-image>
        </view>
        <uv-image @click="save" src="/static/img/audioSave.png" width="40px" height="40px"></uv-image>
      </view>

      <!-- @touchstart.stop="voiceBegin" @touchend.stop="voiceEnd" -->
      <view class="icon" v-else @click="actionAudio">
        <view class="iconQr"></view>
        <uv-image v-if="isRecording" src="/static/img/audioLoading.png" width="80px" height="80px"></uv-image>
        <uv-image v-else src="/static/img/tape.png" width="80px" height="80px"></uv-image>
      </view>
      <view class="fz16 voiceTips">{{voiceTips}}</view>
    </view>
  </uv-popup>
</template>

<script setup lang="ts">
import H5Recorder from "@/utils/H5Recorder.js";
const { proxy } = getCurrentInstance();
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
let props = defineProps(["ruquest", "needFile"]);
const emit = defineEmits(["update:modelValue"]);

let recordContent = ref("");
let timer = ref(null); //定时器
let Audio = uni.createInnerAudioContext();
// #ifdef H5
let recorder = new H5Recorder(); //H5实例
// #endif

// #ifndef H5
let Recorder = uni.getRecorderManager(); //APP实例
// #endif

let voiceTime = ref(0);
let tapeDuration = 60; //录音的最长时间
let voiceTips = ref("点击录音");
let isRecording = ref(false); //是否正在录音
let isPlay = ref(false);

onMounted(() => {
  //录音结束事件
  // #ifndef H5
  Recorder.onStop((res) => {
    getAudioUrl(res.tempFilePath);
  });
  // #endif

  //音频自然播放结束事件
  Audio.onEnded(() => {
    console.log("音频自然播放结束");
    stopAudio();
  });

  //this.hasAuthority()//获取权限
});

async function getAudioUrl(e) {
  if (props.needFile && props.needFile == 1) {
    recordContent.value = e;
  } else if (props.ruquest) {
    recordContent.value = await counter.uploadFile(e, props.ruquest);
  } else {
    // #ifndef H5
    recordContent.value = await counter.uploadFile(e);
    // #endif

    // #ifdef H5
    recordContent.value = await counter.qiNiuUpload(e);
    // #endif
  }
  console.log("上传音频成功", recordContent.value);
}

let open = async () => {
  // #ifdef H5
  let resp = await recorder.init();
  if (!resp) return;
  // #endif

  // #ifdef APP-PLUS
  let ret = await counter.permissionFunc("record");
  if (!ret) return;
  // #endif

  instance.refs.popup.open("bottom");
};

let change = (e) => {
  if (!e.show) init();
};

function init() {
  recordContent.value = "";
  clearTimer(); //清楚定时器
  voiceTime.value = 0;
  stopAudio();
  voiceTips.value = "点击录音";
  isPlay.value = false;
  isRecording.value = false;
}

function actionAudio() {
  if (isRecording.value) {
    voiceEnd();
  } else {
    voiceBegin();
  }
}

async function voiceBegin() {
  console.log("开始录音");

  // #ifdef H5
  recorder.startRecording();
  // #endif

  //#ifndef H5
  Recorder.start();
  // #endif
  timeStart();
  isRecording.value = true;
  voiceTips.value = "再点击 结束";
}

//倒计时开始
function timeStart() {
  timer.value = setInterval(() => {
    if (isRecording.value) {
      voiceTime.value++;
      // 最长不超过15秒
      if (voiceTime.value >= tapeDuration) {
        voiceEnd();
      }
    } else {
      clearTimer();
    }
  }, 1000);
}

async function voiceEnd() {
  console.log("录音结束");
  clearTimer(); //清楚定时器
  voiceTips.value = "点击播放";
  isRecording.value = false;

  // #ifdef H5
  await recorder.stopRecording();
  setTimeout(() => {
    let resp = recorder.exportRecording();
    console.log("H5音频本地文件", resp);
    getAudioUrl(resp);
  }, 1000);
  // #endif

  // #ifndef H5
  Recorder.stop();
  // #endif
}

function clearTimer() {
  clearInterval(timer.value);
  timer.value = null;
}

// 控制播放还是暂停音频文件
function handleAudio() {
  Audio.paused ? playAudio() : stopAudio();
}

//播放音频
function playAudio() {
  Audio.src = recordContent.value;
  Audio.play();
  isPlay.value = true;
}

function stopAudio() {
  Audio.src = "";
  Audio.stop();
  isPlay.value = false;
}

function save() {
  emit("update:modelValue", recordContent.value);
  init();
  instance.refs.popup.close();
}

defineExpose({ open });
</script>



<style lang="scss" scoped>
.audio-container {
  padding: 15px 15px 25px 15px;
  .playIcon {
    margin: 0 20px;
    .playNow {
      border-radius: 50%;
      width: 73px;
      height: 73px;
      background-color: #9e06ff;
      border: 4px solid #d99fff;
      position: relative;
      .pauseIcon {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
  ::v-deep .icon {
    position: relative;
    width: 80px;
    margin: 13px auto;
    .iconQr {
      position: absolute;
      width: 100%;
      height: 100%;
      z-index: 2;
    }
    image {
      pointer-events: none;
      -webkit-pointer-events: none;
      -ms-pointer-events: none;
      -moz-pointer-events: none;
    }
  }
  .icon::before {
    content: " ";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: transparent;
    opacity: 0;
  }
  .time {
    font-size: 20px;
    margin-bottom: 15px;
  }
  .voiceTips {
    margin-top: 15px;
  }
}
</style>

